package com.home.security.browser.manager.factory;

import com.home.common.constants.Constants;
import com.home.common.utils.ip.AddressUtils;
import com.home.common.utils.servlet.ServletUtils;
import com.home.common.utils.spring.SpringUtils;
import com.home.common.utils.string.StringUtils;
import com.home.security.browser.auth.entity.SysOperLog;
import com.home.security.browser.auth.service.SysLoginRecordServer;
import com.home.security.browser.auth.service.SysOperLogService;
import com.home.security.browser.auth.service.SysUserOnlineService;
import com.home.security.browser.manager.session.SysLoginRecord;
import com.home.security.browser.manager.session.SysUserOnline;
import com.home.security.browser.shiro.ShiroUtils;
import com.home.security.browser.utils.LogUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.TimerTask;

/**
 * Description: 异步工厂（产生任务用）
 * Created by 王大宸 on 2020-10-08 19:14
 * Created with IntelliJ IDEA.
 */
public class AsyncFactory {
    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    /**
     * 同步session到数据库
     *
     * @param online 在线用户会话
     * @return 任务task
     */
    public static TimerTask syncSessionToDb(final SysUserOnline online) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = ShiroUtils.getIp();
        return new TimerTask() {
            @Override
            public void run() {
                // 获取客户端操作系统
                // String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                // String browser = userAgent.getBrowser().getName();

                online.setSessionId(String.valueOf(ShiroUtils.getSessionId()));
                online.setIpaddr(ip);
                online.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
                online.setBrowser(userAgent.getBrowser().getName());
                online.setOs(userAgent.getOperatingSystem().getName());
                SpringUtils.getBean(SysUserOnlineService.class).saveOnline(online);
            }
        };
    }

    /**
     * 操作日志记录
     *
     * @param operLog 操作日志信息
     * @return 任务task
     */
    public static TimerTask recordOper(final SysOperLog operLog) {
        return new TimerTask() {
            @Override
            public void run() {
                // 远程查询操作地点
                operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
                SpringUtils.getBean(SysOperLogService.class).save(operLog);
            }
        };
    }

    /**
     * 登录记录入库记录信息
     *
     * @param username 登录账号
     * @param name     姓名
     * @param clientId 客户端
     * @param status   状态
     * @param message  消息
     * @param args     列表
     * @return 任务task
     */
    public static TimerTask recordLogininfor(final String username,
                                             final String name,
                                             final String clientId,
                                             final String status,
                                             final String message,
                                             final Object... args) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = ShiroUtils.getIp();
        return new TimerTask() {
            @Override
            public void run() {
                String address = AddressUtils.getRealAddressByIP(ip);
                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(ip));
                s.append(address);
                s.append(LogUtils.getBlock(username));
                s.append(LogUtils.getBlock(status));
                s.append(LogUtils.getBlock(message));
                // 打印信息到日志
                sys_user_logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                SysLoginRecord logininfor = new SysLoginRecord();
                logininfor.setLoginName(username);
                logininfor.setIpaddr(ip);
                logininfor.setName(name);
                logininfor.setSessionId(String.valueOf(ShiroUtils.getSession().getId()));
                logininfor.setLoginLocation(address);
                logininfor.setClientId(clientId);
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(message);
                logininfor.setLoginTime(LocalDateTime.now());
                // 日志状态
                if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
                    logininfor.setStatus(Constants.SUCCESS);
                } else if (Constants.LOGIN_FAIL.equals(status)) {
                    logininfor.setStatus(Constants.FAIL);
                }
                // 插入数据
                SpringUtils.getBean(SysLoginRecordServer.class).save(logininfor);
            }
        };
    }

}
